package cn.le;

import cn.le.quartz.QuartzExectueJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.spi.MutableTrigger;

import java.util.concurrent.TimeUnit;

/**
 * 项目名  spring-boot
 * Created by lansp
 * Created at 2018/5/21
 * 描述:
 */
public class App {

	public static void main(String[] args) throws SchedulerException, InterruptedException {
		 /*
        *在 Quartz 中， scheduler 由 scheduler 工厂创建：DirectSchedulerFactory 或者StdSchedulerFactory。第二种工厂 StdSchedulerFactory 使用较多，
        *因为 DirectSchedulerFactory 使用起来不够方便，需要作许多详细的手工编码设置。
        */
		// 获取Scheduler实例
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
		scheduler.start();
		System.out.println("scheduler.start");
		//具体任务.
		JobDetail jobDetail = JobBuilder.newJob(QuartzExectueJob.class).withIdentity("job1","group1").build();
		jobDetail.getJobDataMap().put("1","1");
		//触发时间点. (每5秒执行1次.)
		SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever();
		Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1","group1").startNow().withSchedule(simpleScheduleBuilder).build();
		// 交由Scheduler安排触发
		scheduler.scheduleJob(jobDetail,trigger);
		//睡眠20秒.

		TimeUnit.SECONDS.sleep(20);
		System.out.println("修改任务调度器调度时间");
		/** 方式一 ：调用 rescheduleJob 开始 */
		// 触发器
		TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
		// 触发器名,触发器组
		triggerBuilder.withIdentity("trigger1", "group1");
		triggerBuilder.startNow();
		// 触发器时间设定
		SimpleScheduleBuilder simple = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).repeatForever();
		triggerBuilder.withSchedule(simple);
		// 创建Trigger对象
		MutableTrigger mutableTrigger = (MutableTrigger) triggerBuilder.build();
		// 方式一 ：修改一个任务的触发时间
		//TriggerKey.triggerKey(triggerName, triggerGroupName)
		scheduler.rescheduleJob(mutableTrigger.getKey(), mutableTrigger);

		//withIdentity(trigger.getKey()).withSchedule(scheduleBuilder).build();
		// 按新的trigger重新设置job执行
		//scheduler.rescheduleJob(mutableTrigger.getKey(), mutableTrigger);

		TimeUnit.SECONDS.sleep(10);
		scheduler.shutdown();//关闭定时任务调度器.
		System.out.println("scheduler.shutdown");
	}

}
